const redis = require('redis');
require('dotenv').config();

const client = redis.createClient({
  url: `redis://:${process.env.REDIS_PASSWORD}@${process.env.REDIS_HOST}:${process.env.REDIS_PORT}/${process.env.REDIS_DB}`,
});

// 新增通配符删除方法
client.deletePattern = async (pattern) => {
  try {
    // 使用 SCAN 命令安全遍历（推荐生产环境使用）
    const foundKeys = [];
    let cursor = '0';
    
    do {
      const reply = await client.scan(
        cursor,
        'MATCH', pattern,
        'COUNT', 100 // 每次扫描数量
      );
      
      cursor = reply.cursor;
      foundKeys.push(...reply.keys);
    } while (cursor !== '0');

    // 批量删除找到的键
    if (foundKeys.length > 0) {
      // 使用管道提升性能
      const pipeline = client.multi();
      foundKeys.forEach(key => pipeline.del(key));
      await pipeline.exec();
    }
    
    return foundKeys.length;
  } catch (error) {
    console.error('Redis deletePattern error:', error);
    throw error;
  }
};

client.on('error', (err) => {
  console.error('Redis 客户端出错:', err);
});

client.connect().catch(console.error);

module.exports = client;